import axios from "axios";
import { message } from 'ant-design-vue'
import type { RequestParams } from "@/ts-type";

import useUserStore from "@/stores/user";

const instance = axios.create({
    timeout: 15000,
    headers: { "Content-Type": "application/json; charset=utf-8" },
});

// 添加请求拦截器
instance.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    const { token } = useUserStore()
    if (token) {
        config.headers["Authorization"] = token
    } else {
        config.headers["Authorization"] = ""
    }
    return config;
}, function (error) {
    // 对请求错误做些什么

    return Promise.reject(error);
});

// 添加响应拦截器
instance.interceptors.response.use(function (response) {
    // 对响应数据做点什么
  
    return response;

}, function (error) {
    // 对响应错误做点什么 
    if(error.response.data.code !=200) {
        message.error(error.response.data.message+'，请重新登录')
    }
    const status = error.response.status
    switch (status) {
        case 404:
            message.error(error.message)
            break;
    }

    return Promise.reject(error);
});
const request = (options: RequestParams): Promise<any> => {

    return new Promise((resolve, reject) => {
        if (options.method == 'GET' || options.method == 'DELETE') {
            instance.request({
                url: options.url,
                method: options.method,
                params: options.data
            }).then((response) => {
                if (response.status == 200) {
                    resolve(response.data);

                } else {
                    message.error('出错了')
                    reject(response)
                }
            })
        }
        if (options.method == 'POST' || options.method == 'PUT') {
            instance.request({
                url: options.url,
                method: options.method,
                data: options.data,
            }).then((response) => {
                if (response.status == 200) {
                    resolve(response.data);

                } else {
                    message.error('出错了')
                    reject(response)
                }
            })
        }
    })
}
export default request